package com.chukun.disruptor.netty.handler;


import com.chukun.disruptor.netty.bean.TranslatorData;
import com.chukun.disruptor.netty.disruptor.factory.RingBufferWorkerPoolFactory;
import com.chukun.disruptor.netty.disruptor.producer.MessageProducer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 创建client的handler
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 建立连接之后，回调此方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i <10 ; i++) {
            TranslatorData request = new TranslatorData();
            request.setId("start id: "+i);
            request.setName("start name : "+i);
            request.setMessage("message : "+i);
            ctx.writeAndFlush(request);
        }
    }

    /**
     * 客户端收到响应之后，回调此方法
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        TranslatorData translatorData = (TranslatorData) msg;
        String clientProducerID = "code:sessionID:002";
        MessageProducer messageProducer = RingBufferWorkerPoolFactory.getInstance().getMessageProducer(clientProducerID);
        messageProducer.onData(translatorData,ctx);
    }
}
